package com.to8to.autotask.fix;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.to8to.autotask.rpc.SendMsg2ES;
import com.to8to.autotask.util.DBOperaType;
import com.to8to.autotask.util.DBUtil;
import com.to8to.autotask.util.Utils;
import com.to8to.es.db.dao.DBTables;

/**
 * FixJGTime.java
 * 作 者：atom.liu
 * 版 本：v2.0
 * 日 期：2014年12月12日
 * 描 述：初始时修复竣工时间，如果没有竣工时间，则设置。
 *     修改成了sql实现，此类暂时不需要使用。
 */
public class FixJGTime
{
    private static final Logger logger = LoggerFactory.getLogger(FixJGTime.class);

    public static void fix()
    {
        logger.info("修复中标记录的竣工时间开始...");

        Connection connect = null;

        List<String> updateSqlList = new ArrayList<String>();
        List<String> updateZidList = new ArrayList<String>();
        //ftime小于今天天的，没有jg_time的。
        String sql =
            "select * from to8to_jj_smt_zb z left join to8to_jj_smt_sqfk f on z.zid = f.zid where z.ftime < '%s' and z.ftime != '0000-00-00' and jg_time = 0 and iscostbzj in (1,3) order by z.zid";
        String updateSql = "update to8to_jj_smt_zb set jg_time = %s where zid = %s";
        try
        {
            connect = DBUtil.getConnection(false);

            PreparedStatement stat = connect.prepareStatement(String.format(sql, Utils.getTodayStr()));
            ResultSet result = stat.executeQuery();
            while (result.next())
            {
                int zid = result.getInt("zid");
                int ftime = (int) (result.getDate("z.ftime").getTime() / 1000);
                int f_puttime = result.getInt("f.puttime");
                int jg_time = ftime;
                if (f_puttime != 0 && f_puttime < ftime)
                {
                    jg_time = f_puttime;
                }

                logger.info(String.format("更新[ %s ]竣工时间[ %s ]！合同结束时间：%s, 申请返款时间：%s", zid, jg_time, ftime, f_puttime));
                updateSqlList.add(String.format(updateSql, jg_time, zid));
                updateZidList.add(String.valueOf(zid));
            }
            DBUtil.releaseSource(result, stat, null);
            DBUtil.refresh2DB(connect, updateSqlList, -1, new SendMsg2ES(DBOperaType.UPDATE, DBTables.TABLE_ZB, updateZidList));

            logger.info("修复中标记录的竣工时间结束...");
        }
        catch (SQLException e)
        {
            logger.info("修复中标记录的竣工时间异常！" + e.getMessage(), e);
            DBUtil.rollback(connect);
        }
        finally
        {
            DBUtil.releaseSource(null, null, connect);
        }
    }

    public static void main(String[] args)
    {
        fix();
    }
}
